package com.snail.readyvr.activity;

import android.Manifest;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.snail.gift.GiftClient;
import com.snail.gift.GiftClientCaller;
import com.snail.readyvr.R;
import com.snail.readyvr.di.module.ApplicationModule;
import com.snail.readyvr.mvp.model.AccountInfo;
import com.snail.readyvr.mvp.model.MsgParam;
import com.snail.readyvr.util.AppUtils;
import com.snail.readyvr.util.IntentParams;
import com.snail.readyvr.util.LogUtils;
import com.snail.readyvr.util.StringUtils;
import com.snail.readyvr.util.ToastUtils;
import com.snail.readyvr.util.Utils;
import com.snailvr.tv.ui.activity.PlayActivity;
import com.unity3d.player.UnityPlayer;

import java.io.UnsupportedEncodingException;

import butterknife.BindView;
import butterknife.OnClick;
import party.loveit.iflytek.core.SpeechResult;
import party.loveit.iflytek.interfaces.SpeechResultListener;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;

import static com.snail.readyvr.di.module.ApplicationModule.DANMU_HOST_PORT;
import static com.unity3d.player.UnityPlayer.UnitySendMessage;

public class UnityPlayerActivity extends CheckPermissionsActivity implements GiftClientCaller, SpeechResultListener {
    protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code
    @BindView(R.id.unity_player_layout)
    FrameLayout mUnityPlayerLayout;
   /* @BindView(R.id.unity_loading_layout)
    LinearLayout mUnityLoadingLayout;*/
    @BindView(R.id.count_number)
    ImageView count_number;
    @BindView(R.id.countPanel)
    FrameLayout countPanel;

    /*private Animation number_animation;
    private Subscription sub;*/

    private boolean mHasCountTimeFinished = false;
    private boolean mHasSendInitMsg = false;

    private int maxVolume = 0;
    private int mCurVolume = 0;
    private AccountInfo mAccountInfo = new AccountInfo();

    private GiftClient mGiftClient;

    private String mToken;

    private String mRoomId;

    private boolean mHasConnectedGift = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        needPermissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO};
        mGiftClient = new GiftClient();
        mGiftClient.initialize(this, false);
        mAccountInfo.setHead_icon("system1");
        mAccountInfo.setNickname("account_test");
        mToken = getIntent().getStringExtra(IntentParams.UNITY_TOKEN_PARAM);
        mRoomId = getIntent().getStringExtra(IntentParams.UNITY_ROOMID_PARAM);
        startLoginGift();
        mHasSendInitMsg = false;
        enableSystemBarTint(false,0,0);
        isFullScreen = true;
        isCheckDangerousPermission = true;
        super.onCreate(savedInstanceState);
        if (getIntent().hasExtra(IntentParams.UNITY_ACCOUNT_PARAM))
            mAccountInfo = (AccountInfo) getIntent().getSerializableExtra(IntentParams.UNITY_ACCOUNT_PARAM);
        //LogUtils.d(mAccountInfo.getNickname() + "  nn");
        getWindow().setFormat(PixelFormat.RGBX_8888); // <--- This makes xperia play happy
        LogUtils.d(TAG + "-->onCreate");
        /*number_animation = AnimationUtils.loadAnimation(this, R.anim.counting_in_out);
        number_animation.setRepeatCount(0);//设置重复次数
        number_animation.setFillAfter(true);//动画执行完后是否停留在执行完的状态*/
        //startCountTime();
        Glide.with(this).load(R.drawable.unity_tip).asGif().fitCenter().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(count_number);
    }

    private void startLoginGift() {
        //gift.readyvr.woniucloud.com

        if (mGiftClient != null) {
            LogUtils.d("开始登陆");
            Observable.just(1)
                    //.delay(3, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Integer>() {
                        @Override
                        public void onCompleted() {

                            mGiftClient.login(ApplicationModule.DANMU_HOST, DANMU_HOST_PORT, mRoomId, mToken);
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(Integer integer) {

                        }
                    });
        }
    }
/*
    private void startCountTime() {
        mHasCountTimeFinished = false;
        final int countTime = 5;
        sub = Observable.interval(0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<Long, Integer>() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1).subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {

                        if (integer == 5) {
                            count_number.setImageResource(R.drawable.count_five);
                            count_number.startAnimation(number_animation);
                        } else if (integer == 4) {
                            count_number.setImageResource(R.drawable.count_four);
                            count_number.startAnimation(number_animation);
                        } else if (integer == 3) {
                            count_number.setImageResource(R.drawable.count_three);
                            count_number.startAnimation(number_animation);
                        } else if (integer == 2) {
                            count_number.setImageResource(R.drawable.count_two);
                            count_number.startAnimation(number_animation);
                        } else if (integer == 1) {
                            count_number.setImageResource(R.drawable.count_one);
                            count_number.startAnimation(number_animation);
                        } else if (integer == 0) {
                            // 跳转
                            //IntentUtils.playRealVideo(PlayHintActivity.this, PATH, NAME, false);
                            mHasCountTimeFinished = true;
                           *//* if (hasGetDangerousPermission && hasGetAllPermissions && !mHasSendInitMsg) {
                                mHasSendInitMsg = true;
                                UnitySendMessage("VRManager", "Init", getIntent().getStringExtra(IntentParams.UNITY_PARAM));
                            }*//*
                            countPanel.setVisibility(View.GONE);
                        }
                    }
                });
    }*/

    // Quit Unity
    @Override
    protected void onDestroy() {
        LogUtils.d(TAG + "-->onDestroy");
        if (hasGetAllPermissions)
            SpeechResult.getInstance().unRegister(this);
        if (mGiftClient != null)
            mGiftClient.logout();
        /*if (sub != null && !sub.isUnsubscribed()) {
            sub.unsubscribe();
        }*/
        if (mUnityPlayer != null)
            mUnityPlayer.quit();
        super.onDestroy();
    }

    // Pause Unity
    @Override
    protected void onPause() {
        LogUtils.d(TAG + "-->onPause");
        super.onPause();
        if (mUnityPlayer != null)
            mUnityPlayer.pause();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_unity;
    }

    @Override
    protected void init() {


    }

    // Resume Unity
    @Override
    protected void onResume() {
        LogUtils.d(TAG + "-->onResume");
        super.onResume();
        if (mUnityPlayer != null)
            mUnityPlayer.resume();
    }

    // This ensures the layout will be correct.
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mUnityPlayer != null)
            mUnityPlayer.configurationChanged(newConfig);
    }

    // Notify Unity of the focus change.
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (mUnityPlayer != null)
            mUnityPlayer.windowFocusChanged(hasFocus);
    }

    // For some reason the multiple keyevent type is not supported by the ndk.
    // Force event injection by overriding dispatchKeyEvent().
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_MULTIPLE && mUnityPlayer != null)
            return mUnityPlayer.injectEvent(event);
        return super.dispatchKeyEvent(event);
    }

    // Pass any events not handled by (unfocused) views straight to UnityPlayer
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (mUnityPlayer != null)
            return mUnityPlayer.injectEvent(event);
        else
            return super.onKeyUp(keyCode, event);
    }

    /**
     * 开启语音监听
     */
    public void startSpeech(){
        SpeechResult.getInstance().startSpeech();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK) {
            if (hasGetAllPermissions) {
                SpeechResult.getInstance().startSpeech();
                LogUtils.d("unity speech");
            }
        }

        if (keyCode == KeyEvent.KEYCODE_BACK)
            onClick();

        if (mUnityPlayer != null)
            return mUnityPlayer.injectEvent(event);
        else
            return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void hasGetAllPermissions() {
        SpeechResult.init(this, false);
        SpeechResult.getInstance().register(this);
        mUnityPlayer = new UnityPlayer(this);
        mUnityPlayerLayout.addView(mUnityPlayer);
        mUnityPlayer.requestFocus();
        maxVolume = AppUtils.getMaxVolume(this);
        mCurVolume = AppUtils.getCurVolume(this);
        /*if (mHasCountTimeFinished && !mHasSendInitMsg) {
            mHasSendInitMsg = true;
            UnitySendMessage("VRManager", "Init", getIntent().getStringExtra(IntentParams.UNITY_PARAM));
        }*/
        UnitySendMessage("VRManager", "Init", getIntent().getStringExtra(IntentParams.UNITY_PARAM));
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mUnityPlayer != null)
            return mUnityPlayer.injectEvent(event);
        else
            return super.onTouchEvent(event);
    }

    /*API12*/
    public boolean onGenericMotionEvent(MotionEvent event) {
        if (mUnityPlayer != null)
            return mUnityPlayer.injectEvent(event);
        else
            return super.onGenericMotionEvent(event);
    }

    @OnClick(R.id.unity_back)
    public void onClick() {
        UnitySendMessage("VRManager", "DestroyUnity", "");
        //if(mUnityPlayer != null)
        //UnityPlayer.UnitySendMessage();
    }

    /**
     * 获取声音
     *
     * @return
     */
    public float getVolume() {
        if (maxVolume > 0 && hasGetDangerousPermission) {
            // LogUtils.d("getVolume   mid");
            float a = Utils.formatFloat((float) mCurVolume / (float) maxVolume);
            return a;
        }
        return 0;
    }

    /**
     * 设置声音
     */
    public void setVolume(float volume) {
        if (hasGetDangerousPermission)
            AppUtils.setVolume(this, (int) (volume * maxVolume));

    }

    /**
     * 加载完成
     */
    public void loadComplete() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                countPanel.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 从unity退到app
     *
     * @param json
     */
    public void unityToNative(String json) {
        LogUtils.d(json);
        if (StringUtils.isJson(json)) {
            /*  ChannelInfoResponBean.DataBean dataBean = JSON.parseObject(json, ChannelInfoResponBean.DataBean.class);
          UnityBack back = new UnityBack();
            if (dataBean != null)
                back.setChannelid(dataBean.getId());
            if (dataBean != null && dataBean.getDefault_room_info() != null)
                back.setRoomId(dataBean.getDefault_room_info().getId());*/
            Intent intent = new Intent();
            intent.putExtra(IntentParams.UNITY_BACK_PARAM, json);
            setResult(PlayActivity.RESULT_UNITY_CODE, intent);
        }

        finish();
    }

    public void changeRoomID(int roomid) {
        mRoomId = roomid + "";
        if (mGiftClient != null)
            mGiftClient.logout();
        startLoginGift();


    }

    /**
     * 发送消息
     *
     * @param message
     */
    public void sendMessage(String message) {
        if (!mHasConnectedGift) {
          ToastUtils.show(this, R.string.no_connect_tip);
            /*if(mGiftClient!=null) {
                if (mGiftClient.getLoginStatus()==0)
                    mGiftClient.login(ApplicationModule.DANMU_HOST, DANMU_HOST_PORT, mRoomId, mToken);
            }*/
            return;
        }
        if (mGiftClient != null && message != null) {
            try {
                mGiftClient.sendMessage(new String(message.getBytes(), "utf-8"), "", this);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给主播发送消息
     *
     * @param message
     */
    public void sendMsgToUp(String message) {
        if (!mHasConnectedGift) {
          ToastUtils.show(this, R.string.no_connect_tip);
            /*if(mGiftClient!=null) {
                if (mGiftClient.getLoginStatus()==0)
                    mGiftClient.login(ApplicationModule.DANMU_HOST, DANMU_HOST_PORT, mRoomId, mToken);
            }*/
            return;
        }
        if (mGiftClient != null && message != null) {
            try {
                mGiftClient.sendToAnchorMessage(new String(message.getBytes(), "utf-8"), "", this);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送礼物
     *
     * @param message
     */
    public void sendGiftMessage(String message) {
        if (!mHasConnectedGift) {
            ToastUtils.show(this, R.string.no_connect_tip);
            return;
        }
        if (mGiftClient != null && message != null) {
            try {
                mGiftClient.sendGiftMessage(new String(message.getBytes(), "utf-8"), "", this);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onLoginComplete(boolean loginResult) {
        mHasConnectedGift = loginResult;
        if (!loginResult)
            startLoginGift();
        LogUtils.d("onLoginComplete-->" + loginResult);
    }

    @Override
    public void onDisconnect(int disconnectType) {
        mHasConnectedGift = false;
        LogUtils.d("onDisconnect-->" + disconnectType);
        if(disconnectType != 1)
          startLoginGift();
    }

    @Override
    public void onSendMessageComplete(boolean sendResult, Object context) {
        LogUtils.d("onSendMessageComplete-->" + sendResult);
    }

    @Override
    public void onSendGiftMessageComplete(boolean sendResult, Object context) {
        LogUtils.d("onSendGiftMessageComplete-->" + sendResult);
    }

    @Override
    public void onReceiveMessage(String message, String reserved,  String uid, String nickName, String icon, int type) {
        LogUtils.d("onReceiveMessage-->" + message);
        MsgParam param = new MsgParam(message, icon, nickName, "", type);
        try {
            UnitySendMessage("VRManager", "GetMessage", new String(JSON.toJSONString(param).getBytes(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        LogUtils.d("onReceiveMessage param-->" + JSON.toJSONString(param));
    }

    @Override
    public void onReceiveGiftMessage(String giftId, String reserved,  String uid,String nickName, String icon) {
        LogUtils.d("onReceiveGiftMessage-->" + giftId);
        MsgParam param = new MsgParam(giftId, icon, nickName, "", 0);
        try {
            UnitySendMessage("VRManager", "GetGiftMessage", new String(JSON.toJSONString(param).getBytes(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        LogUtils.d("onReceiveGiftMessage param-->" + JSON.toJSONString(param));
    }

    @Override
    public void onUserLogin( String uid, String nickName, int userType, String icon) {

    }

    @Override
    public void onUserLogout( String uid, String nickName) {

    }

    @Override
    public void onUserInfoChanged( String uid, String s, int i, String s1) {

    }

    @Override
    public void onSpeechPause() {
        UnitySendMessage("VRManager", "SpeachResult", "暂停");
    }

    @Override
    public void onSpeechPlay() {
        UnitySendMessage("VRManager", "SpeachResult", "播放");
    }

    @Override
    public void onSpeechNext() {
        UnitySendMessage("VRManager", "SpeachResult", "换台");
    }

    @Override
    public void onSpeechPrevious() {
        UnitySendMessage("VRManager", "SpeachResult", "上一个");
    }

    @Override
    public void onSpeechPositive() {
        UnitySendMessage("VRManager", "SpeachResult", "回正");
    }

    @Override
    public void onSpeechDanMu(String result) {
        /*if (mGiftClient != null && result != null) {
            try {
                mGiftClient.sendMessage(new String(result.getBytes(), "utf-8"), "", this);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }*/
        UnitySendMessage("VRManager", "SpeachResult", result);
    }

    @Override
    public void onSpeechResult(String result) {

    }
}
